package com.shijie.controller.erp;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.shijie.component.ErpUserService;
import com.shijie.core.Result;
import com.shijie.core.ResultGenerator;
import com.shijie.core.ServiceException;
import com.shijie.core.annotation.Log;
import com.shijie.core.annotation.NoLogin;
import com.shijie.core.constants.PnConstant.BusinessType;
import com.shijie.domain.entity.Admins;
import com.shijie.domain.enums.EnumInterface;
import com.shijie.service.AdminsService;
import com.shijie.service.RolesService;
import com.shijie.utils.HttpUtil;
import com.shijie.utils.MD5Util;

@RestController
@RequestMapping("/erp")
public class LoginController {
	private Logger logger = LoggerFactory.getLogger(LoginController.class);
	@Autowired
	private AdminsService adminsService;
	@Autowired
	private ErpUserService erpUserService;
	@Resource
	private RolesService rolesService;

	@Log(title = "用户登录", action = BusinessType.INSERT)
	@PostMapping("login")
	@NoLogin
	public Result add(HttpServletRequest request, @RequestBody Admins admin)
			throws ServiceException {
		// 用户名或密码为空 错误
		if (StringUtils.isEmpty(admin.getLoginName())
				|| StringUtils.isEmpty(admin.getPassword())) {
			logger.error(String.format("%s用户名或密码为空。", admin.getLoginName()));
			throw new ServiceException(String.format("%s用户名或密码为空。",
					admin.getLoginName()));
		}
		// 查询用户信息
		Admins adminx = adminsService.getAdminByLoginNameAndPassword(
				admin.getLoginName(), null);

		if (adminx == null
				|| (EnumInterface.Status.VALID.ordinal() != adminx.getStatus())) {
			throw new ServiceException(String.format("%s不存在。",
					admin.getLoginName()));
		}

		if (EnumInterface.Status.VALID.ordinal() != adminx.getStatus()) {
			throw new ServiceException(String.format("%s状态不可用。",
					admin.getLoginName()));
		}
		if(!matches(adminx, admin.getPassword())){
			throw new ServiceException(String.format("%s密码错误。",
					admin.getLoginName()));
		}
		// 插入用户权限列表到缓存
		erpUserService.createToken(adminx);

		// 更新用户登录信息
		Admins updateAdmin = new Admins();
		updateAdmin.setUpdateBy(admin.getUserName());
		updateAdmin.setUpdateTime(DateTime.now().toDate());
		updateAdmin.setLoginIp(HttpUtil.getIpAddress(request));
		updateAdmin.setLoginDate(DateTime.now().toDate());
		updateAdmin.setId(adminx.getId());
		adminsService.updateById(updateAdmin);
		return ResultGenerator.success(adminx);
	}

	public boolean matches(Admins admin, String newPassword) {
		return admin.getPassword().equals(
				encryptPassword(admin.getLoginName(), newPassword,
						admin.getSalt()));
	}

	public String encryptPassword(String username, String password, String salt) {
		return MD5Util.MD5Encode(username + password + salt, "UTF-8").toString();
	}
}
